package com.dave.admin.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * 水印工具
 *
 * @author Dave
 */
public class WaterMarkUtils {


    public static void main(String[] args) {

    }

    public static void markByText(String sourceImage, String out, String imageType, String text) {
        try {
            File source = new File(sourceImage);
            Image s = ImageIO.read(source);
            int s_width = s.getWidth(null);
            int s_heigth = s.getHeight(null);
            BufferedImage bufferedImage = new BufferedImage(s_width, s_heigth, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2d = bufferedImage.createGraphics();
            graphics2d.drawImage(s, 0, 0, s_width, s_heigth, null);


            int[] fontSizes = {140, 120, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 8, 5};
            int fontSize = fontSizes[8];
            Font font = new Font("宋体", Font.PLAIN, fontSize);

            for (int size : fontSizes) {
                // 当前的图片宽度 - 最大号的字体得出来的宽度 = 正数 （说明在图片内） | 还要大于一般至少在右边
                if ((s_width - size * getTextLength(text)) > (s_width / 2 + 60)) {
                    font = new Font("宋体", Font.PLAIN, size);
                    fontSize = size;
                    break;
                }
            }

            graphics2d.setColor(Color.white);
            graphics2d.setFont(font);

            int x = s_width - fontSize * getTextLength(text);
            int y = s_heigth - fontSize;
            graphics2d.drawString(text, x, y);
            graphics2d.dispose();
            File file = new File(out);
            ImageIO.write(bufferedImage, imageType, file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Finish Mark");
    }

    /**
     * 文本长度的处理：文字水印的中英文字符的宽度转换
     *
     * @param text 文字
     * @return
     */
    public static int getTextLength(String text) {
        int length = text.length();
        for (int i = 0; i < text.length(); i++) {
            String s = String.valueOf(text.charAt(i));
            //中文字符
            if (s.getBytes().length > 1) {
                length++;
            }
        }
        //中文和英文字符的转换
        length = length % 2 == 0 ? length / 2 : length / 2 + 1;
        return length;
    }

}

